//
//  LGNetWorKingManager.swift
//  微博框架
//
//  Created by ming on 16/10/10.
//  Copyright © 2016年 ming. All rights reserved.
//

import UIKit
import AFNetworking
enum HttpMethod {
    case GET
    case POST
}



class LGNetWorKingManager: AFHTTPSessionManager {
    lazy var userAccess = UserAccessInfo()
    
    //用户登录标记
    func accessToken()->(Bool){
        
        
        return userAccess.access_token != nil
    }
    
    
 
    //创建一个单列
    static let shared = { () -> LGNetWorKingManager in
        
            let insstance = LGNetWorKingManager()
            insstance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
            return insstance
    }()
    ///第二中写法
//    static let shared:LGNetWorKingManager = {
//        let insstance = LGNetWorKingManager()
//        insstance.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        
//        return insstance
//    }()

    
    
    
    
    //用一个函数来封装AFN，因为网络请求中一定用到get，post 请求所以先封装这两个
    //get方法
    /// 封装getpost 请求
    ///
    /// - parameter method:     请求方法
    /// - parameter urlString:  请求的地址
    /// - parameter parameters: 请求的参数
    /// - parameter completion: 请求结果回调
    func request(method:HttpMethod = .GET, urlString:String, parameters:[String:String]?,  completion:@escaping (_ json:Any?,_ isSuccess:Bool)->()) {
        
        //先定义两个回调方法，失败回调和成功回调
      
        let success = {(dasks:URLSessionTask?, json:Any?) ->()in
            completion(json, true)
            
        }
        let failure = {(dasks:URLSessionTask?,error:Error?)->()in
            
            let respones = dasks?.response as? HTTPURLResponse
            if respones?.statusCode == 403 {
                print("token过期请重新登录")
                //发送通知通知用户登录
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notificationuserlogin), object: nil)
                
            }else{
                
                print("请求失败%@",error)
            }


            
            completion(nil, false)
        }

        if method == .GET {
            get(urlString, parameters: parameters, progress:nil, success: success, failure: failure)
        }else{
            
            post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }
        
        
    }
    
    func tokenRequest(method:HttpMethod = .GET, urlString:String, parameters:[String:String]?,  completion:@escaping (_ json:Any?,_ isSuccess:Bool)->()){
        
        var parameters = parameters
        if parameters == nil{
            
             parameters = [String:String]();
        }
        guard let token =  userAccess.access_token else {
            print("token为空请处理")
            //通知用户登录获取token
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notificationuserlogin), object: nil)
            return
        }
        //403,token过期处理
        
        
        parameters?["access_token"] = token
        
        request(method: method, urlString: urlString, parameters: parameters, completion: completion)
        
    }
    
    
    
    
}
